package club.gggd.security_jwt_demo.controller;

import club.gggd.security_jwt_demo.pojo.entity.SysUser;
import club.gggd.security_jwt_demo.pojo.module.WebResult;
import club.gggd.security_jwt_demo.pojo.vo.LoginVo;
import club.gggd.security_jwt_demo.service.UserService;
import club.gggd.security_jwt_demo.util.JwtUtil;
import club.gggd.security_jwt_demo.util.UserProvider;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

/**
 * @Description
 * @Author srx
 * @date 2023/12/10 13:35
 */
@RestController
@RequestMapping("/auth")
public class AuthController {

    @Autowired
    private UserService userService;

    @Autowired
    private UserProvider userProvider;

    @Autowired
    private JwtUtil jwtUtil;

    @PostMapping("/login")
    public WebResult login(@RequestBody @Validated LoginVo vo) {
        // 判断验证码，写死，不要学
        if (!"1234".equals(vo.getCode())) {
            return WebResult.error("验证码错误");
        }
        String token = userService.login(vo);
        return WebResult.success((Object) token);
    }

    @PostMapping("/logout")
    public WebResult logout(HttpServletRequest request) {
        jwtUtil.logout(request);
        return WebResult.success();
    }

    @GetMapping("/info")
    public WebResult getUserInfo() {
        String account = userProvider.getAccount();
        SysUser user = userService.getUserByAccount(account);
        return WebResult.success(user);
    }

    @GetMapping("/security")
    @PreAuthorize("@el.check('create_user')")
    public WebResult getSecurityInfo() {
        userProvider.curUser();
        return WebResult.success("获取成功");
    }
}
